package com.dabai.applicationmanager.ui.smallprogram;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dabai.applicationmanager.R;
import com.dabai.applicationmanager.adapter.FreezerAdapter;
import com.dabai.applicationmanager.bean.FreezerAppInfo;
import com.dabai.applicationmanager.dialog.TipAlertDialog;
import com.dabai.applicationmanager.shizuku.Shell;
import com.dabai.applicationmanager.shizuku.ShizukuShell;
import com.dabai.applicationmanager.utils.OtherUtils;
import com.dabai.dbutils.toast.DBToast;
import com.dabai.dbutils.utils.AppUtils;
import com.dabai.dbutils.utils.ShellUtils;
import com.dabai.uitools.base.BaseAppCompatActivity;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import me.zhanghai.android.appiconloader.AppIconLoader;

public class FreezerActivity extends BaseAppCompatActivity {

    Context context;

    RecyclerView recyclerView;
    private ArrayList<FreezerAppInfo> freezerInfos;
    private PackageManager packageManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_freezer);

        context = this;

        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);

        TipAlertDialog.init(context);

        recyclerView = findViewById(R.id.recyclerView);

        recyclerView.setLayoutManager(new GridLayoutManager(this, 4));

        SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);

        swipeRefreshLayout.setOnRefreshListener(() -> {
            swipeRefreshLayout.setRefreshing(false);
        });
        swipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.teal_700));

        queryFiles();

    }


    /**
     * 查询SD卡里安装包
     */
    FreezerAdapter freezerAdapter;

    private void queryFiles() {

        TipAlertDialog.getInstance(context).showTipLayout("正在检查停用应用");

        packageManager = this.getPackageManager();
        AppIconLoader appIconLoader = new AppIconLoader(130, true, context);

        new Thread(() -> {

            freezerInfos = new ArrayList<>();

            List<PackageInfo> packageInfos = AppUtils.getAllInstalledPackages(context);


            for (PackageInfo packageInfo : packageInfos) {

                ApplicationInfo applicationInfo = packageInfo.applicationInfo;
                String appName = packageManager.getApplicationLabel(applicationInfo).toString();

                if (AppUtils.isFreeze(context, packageInfo.packageName)) {
                    freezerInfos.add(new FreezerAppInfo(
                            appIconLoader.loadIcon(applicationInfo)
                            , appName
                            , packageInfo.packageName
                    ));
                }
            }

            //使用数据
            freezerAdapter = new FreezerAdapter(freezerInfos, context);
            freezerAdapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.AlphaIn);

            freezerAdapter.setOnItemClickListener((adapter, view, position) -> {

                if (OtherUtils.getImplementWay(context) == 1 && !AppUtils.isSystemApplication(context, getPackageName())) {
                    DBToast.showText(context, "当前执行方式,不支持启用其他APP!", false);
                    return;
                }

                String packageName = freezerInfos.get(position).getPackageName();

                new MaterialAlertDialogBuilder(context, R.style.DBTheme_Dialog_RoundTheme)
                        .setTitle("提示")
                        .setMessage("是否启用 " + freezerInfos.get(position).getName() + " ?")
                        .setPositiveButton("启用", (dialog12, which12) -> {

                            new Thread(() -> {

                                if (OtherUtils.getImplementWay(context) == 1) {
                                    packageManager.setApplicationEnabledSetting(packageName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0);
                                } else if (OtherUtils.getImplementWay(context) == 2) {
                                    ShellUtils.enableApp(packageName);
                                } else if (OtherUtils.getImplementWay(context) == 3) {
                                    ShizukuShell.getInstance().exec(new Shell.Command(
                                            "pm enable ", packageName));
                                }
                                runOnUiThread(() -> {
                                    DBToast.showText(context, "操作完成!", true);
                                    queryFiles();
                                });
                            }).start();

                        }).setNeutralButton("取消", null)
                        .show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

            });


            runOnUiThread(() -> {
                recyclerView.setAdapter(freezerAdapter);
                setTitle("冷藏室(" + freezerAdapter.getData().size() + ")");
                TipAlertDialog.getInstance(context).hideTipLayout();
            });


        }).start();

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == android.R.id.home) {
            finish();
            return true;
        }
   if (itemId == R.id.enableAll) {

       new MaterialAlertDialogBuilder(context, R.style.DBTheme_Dialog_RoundTheme)
               .setTitle("提示")
               .setMessage("是否启用全部APP?")
               .setPositiveButton("全部启用", (dialog12, which12) -> {

                   if (OtherUtils.getImplementWay(context) == 1 && !AppUtils.isSystemApplication(context, getPackageName())) {
                       DBToast.showText(context, "当前执行方式,不支持启用其他APP!", false);
                       return;
                   }

                   new Thread(() -> {

                       for (FreezerAppInfo freezerAppInfo : freezerInfos){
                           if (OtherUtils.getImplementWay(context) == 1) {
                               packageManager.setApplicationEnabledSetting(freezerAppInfo.getPackageName(), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0);
                           } else if (OtherUtils.getImplementWay(context) == 2) {
                               ShellUtils.enableApp(freezerAppInfo.getPackageName());
                           } else if (OtherUtils.getImplementWay(context) == 3) {
                               ShizukuShell.getInstance().exec(new Shell.Command(
                                       "pm enable ", freezerAppInfo.getPackageName()));
                           }
                       }

                       runOnUiThread(() -> {
                           DBToast.showText(context, "操作完成!", true);
                           queryFiles();
                       });
                   }).start();

               }).setNeutralButton("取消", null)
               .show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

            return true;
        }

        return super.onOptionsItemSelected(item);
    }




    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.freezer, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        TipAlertDialog.destroyTipLayout();
    }
}